package siga.pacotao;

import java.io.BufferedOutputStream;
//import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;

public class atualizar{

        /** Arquivo para update */
        private String urlUpdateFile = "http://192.168.0.1/arquivo/SIGA_SEC.jar";

        /** Faz download de arquivo */
        public void download(String address, String localFileName, String host, int porta) {

                // leitor do arquivo a ser baixado
                InputStream in = null;
                // conexão com a internete
                URLConnection conn = null;
                // escritor do arquivo que será baixado
                OutputStream out = null;

//                System.out.println("Update.download() BAIXANDO " + address);

                try {
                        URL url = new URL(address);
                        out = new BufferedOutputStream(new FileOutputStream(localFileName));
//                        System.out.println(System.getProperty("user.dir"));
                        // verifica se existe proxy
                        if(!host.equals("") && host!=null){
                                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host,porta));
                                conn = url.openConnection(proxy);
                        }else{
                                conn = url.openConnection();
                        }
                        in = conn.getInputStream();
                        byte[] buffer = new byte[1024];
                        int numRead = in.read(buffer);
                        long numWritten = 0;
                        System.out.println(" " + numRead);
                        while (numRead != -1) {
                                out.write(buffer, 0, numRead);
                                numWritten += numRead;
                        }
                        System.out.println(localFileName + "\t" + numWritten);                        
                } catch (Exception ex) {
                        System.out.println(ex.getStackTrace());
                } finally {
                        try {
                                if (in != null) {
                                        in.close();
                                }
                                if (out != null) {
                                        out.close();
                                }
                        } catch (IOException ioe) {
                            System.out.println(ioe.getMessage());
                        }
                }
        }
}